"""
音乐播放器工具实现
只支持实际音频播放的完整版本
"""

import os
import logging
import random
import threading
import time
from typing import List, Optional, Dict, Any
from pathlib import Path

# 尝试导入pygame，如果不可用则抛出错误
try:
    import pygame
    import pygame.mixer
    _pygame_available = True
    logger = logging.getLogger(__name__)
    logger.info("pygame音频播放库可用")
except ImportError:
    pygame = None
    pygame.mixer = None
    _pygame_available = False
    logger = logging.getLogger(__name__)
    logger.error("pygame不可用，音乐播放器无法工作。请运行: pip install pygame==2.5.2")


class SimpleMusicPlayer:
    """完整的音乐播放器类，只支持实际音频播放"""
    
    def __init__(self, music_dir: str = "music"):
        if not _pygame_available:
            raise RuntimeError("pygame库未安装，音乐播放器无法工作。请安装: pip install pygame==2.5.2")
        
        self.music_dir = Path(music_dir)
        self.current_music = None
        self.is_playing = False
        self.volume = 0.7
        self._music_list = []
        self._playback_thread = None
        self._stop_event = threading.Event()
        
        # 创建音乐目录
        self.music_dir.mkdir(exist_ok=True)
        
        # 初始化pygame mixer
        self._init_audio()
        
        # 初始化音乐列表
        self._load_music_list()
        logger.info(f"音乐播放器初始化完成，目录: {self.music_dir}")
    
    def _init_audio(self):
        """初始化音频系统"""
        try:
            pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=512)
            pygame.mixer.music.set_volume(self.volume)
            logger.info("pygame音频系统初始化成功")
        except Exception as e:
            logger.error(f"pygame音频系统初始化失败: {e}")
            raise RuntimeError(f"音频系统初始化失败: {e}")
    
    def _load_music_list(self) -> List[str]:
        """加载音乐文件列表"""
        try:
            if not self.music_dir.exists():
                logger.warning(f"音乐目录不存在: {self.music_dir}")
                self._music_list = []
                return []
            
            # 查找音频文件
            audio_extensions = ['.mp3', '.wav', '.flac', '.m4a', '.ogg']
            files = []
            
            for file in self.music_dir.iterdir():
                if file.is_file() and file.suffix.lower() in audio_extensions:
                    files.append(file.name)
            
            self._music_list = files
            logger.info(f"加载了 {len(files)} 个音乐文件")
            return files
            
        except Exception as e:
            logger.error(f"加载音乐列表失败: {e}")
            self._music_list = []
            return []
    
    def list_music(self) -> List[str]:
        """获取音乐列表"""
        return self._music_list
    
    def _monitor_playback(self):
        """监控播放状态"""
        while not self._stop_event.wait(1.0):
            try:
                if not pygame.mixer.music.get_busy() and self.is_playing:
                    # 音乐自然播放结束
                    logger.info("音乐播放自然结束")
                    self.is_playing = False
                    self.current_music = None
                    break
            except Exception as e:
                logger.error(f"监控播放状态时出错: {e}")
                break
        
        logger.debug("音乐播放监控线程结束")
    
    def play_music(self, music_name: str) -> str:
        """播放指定音乐"""
        try:
            # 查找音乐文件
            music_file = self._find_music_file(music_name)
            if not music_file:
                return f"很抱歉，未找到歌曲《{music_name}》"
            
            # 停止当前播放
            if self.is_playing:
                self.stop_music()
            
            music_path = self.music_dir / music_file
            
            # 实际播放音频
            try:
                pygame.mixer.music.load(str(music_path))
                pygame.mixer.music.set_volume(self.volume)
                pygame.mixer.music.play()
                
                self.current_music = music_file
                self.is_playing = True
                
                # 启动监控线程
                self._stop_event.clear()
                self._playback_thread = threading.Thread(target=self._monitor_playback, daemon=True)
                self._playback_thread.start()
                
                music_title = Path(music_file).stem
                logger.info(f"开始播放音乐: {music_path}")
                return f"🎵 正在为您播放《{music_title}》，音量: {int(self.volume * 100)}%"
                
            except Exception as e:
                logger.error(f"播放失败: {e}")
                return f"播放失败: {str(e)}"
            
        except Exception as e:
            logger.error(f"播放音乐失败: {e}")
            return f"播放失败: {str(e)}"
    
    def play_random_music(self) -> str:
        """随机播放音乐"""
        if not self._music_list:
            return "很抱歉，当前没有可播放的音乐"
        
        random_music = random.choice(self._music_list)
        return self.play_music(random_music)
    
    def stop_music(self) -> str:
        """停止播放音乐"""
        if not self.is_playing:
            return "当前没有正在播放的音乐"
        
        try:
            pygame.mixer.music.stop()
            logger.info("停止音频播放")
        except Exception as e:
            logger.error(f"停止播放失败: {e}")
        
        # 停止监控线程
        self._stop_event.set()
        if self._playback_thread and self._playback_thread.is_alive():
            self._playback_thread.join(timeout=2.0)
        
        self.is_playing = False
        music_title = Path(self.current_music).stem if self.current_music else "未知歌曲"
        self.current_music = None
        
        logger.info(f"停止播放音乐: {music_title}")
        return f"🛑 已停止播放《{music_title}》"
    
    def set_volume(self, volume: float) -> str:
        """设置音量"""
        try:
            # 验证音量范围
            volume = max(0.0, min(1.0, volume))
            self.volume = volume
            
            # 实时调整音量
            try:
                pygame.mixer.music.set_volume(volume)
                logger.info(f"调整音量到: {volume}")
            except Exception as e:
                logger.error(f"音量调整失败: {e}")
            
            percentage = int(volume * 100)
            logger.info(f"音量设置为: {percentage}%")
            return f"🔊 音乐音量已设置为 {percentage}%"
            
        except Exception as e:
            logger.error(f"设置音量失败: {e}")
            return f"设置音量失败: {str(e)}"
    
    def increase_volume(self, step: float = 0.1) -> str:
        """增加音量"""
        new_volume = min(1.0, self.volume + step)
        return self.set_volume(new_volume)
    
    def decrease_volume(self, step: float = 0.1) -> str:
        """减少音量"""
        new_volume = max(0.0, self.volume - step)
        return self.set_volume(new_volume)
    
    def get_current_status(self) -> Dict[str, Any]:
        """获取当前播放状态"""
        return {
            "is_playing": self.is_playing,
            "current_music": self.current_music,
            "volume": self.volume,
            "music_count": len(self._music_list)
        }
    
    def _find_music_file(self, music_name: str) -> Optional[str]:
        """查找音乐文件"""
        # 精确匹配
        if music_name in self._music_list:
            return music_name
        
        # 不带扩展名匹配
        name_without_ext = Path(music_name).stem
        for music_file_item in self._music_list:
            if Path(music_file_item).stem == name_without_ext:
                return music_file_item
        
        # 模糊匹配
        for music_file_item in self._music_list:
            if name_without_ext.lower() in Path(music_file_item).stem.lower():
                return music_file_item
        
        return None


# 全局音乐播放器实例
_music_player_instance: Optional[SimpleMusicPlayer] = None


def get_music_player() -> SimpleMusicPlayer:
    """获取全局音乐播放器实例"""
    global _music_player_instance
    if _music_player_instance is None:
        _music_player_instance = SimpleMusicPlayer()
    return _music_player_instance


def initialize_music_player(music_dir: str = "music"):
    """初始化音乐播放器"""
    global _music_player_instance
    _music_player_instance = SimpleMusicPlayer(music_dir)
    return _music_player_instance